<template>
  <el-form
    size="large"
    :rules="Rules"
    ref="deptForm"
    :model="formData"
    label-width="100px"
  >
    <el-form-item prop="orgName" label="单位名称">
      <el-input clearable placeholder="请输入单位名称" v-model="formData.orgName"></el-input>
    </el-form-item>
    <el-form-item prop="showOrder" label="单位排序">
      <el-input-number v-model="formData.showOrder" :step="5" :min="0"></el-input-number>
    </el-form-item>
    <el-form-item prop="status" label="启用状态">
      <el-switch
        v-model="formData.statusBoolean"
        inline-prompt
        active-text="启用"
        inactive-text="停用"
      ></el-switch>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(deptForm)">保存</el-button>
      <el-button type="info" @click="handleClose">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DeptConfigBean, Rules } from '@/model/business/questions/deptconfig/DeptConfigConstants'
import { getNextShowOrder, getDeptConfigById, saveDeptConfig } from '@/api/business/questions/deptconfig/DeptConfig'

const deptForm = ref()
const props = defineProps({ id: String })
const emit = defineEmits(['close-dialog', 'reload-data'])
const formData = ref({ ...DeptConfigBean })

const handleClose = () => {
  emit('close-dialog')
}

const submitForm = async (deptForm) => {
  if (!deptForm) return
  deptForm.validate(valid => {
    if (valid) {
      saveDeptConfig(formData.value).then((data) => {
        ElMessage({
          message: '保存成功！',
          type: 'success',
          duration: 800
        })
        emit('reload-data')
        emit('close-dialog')
      })
    }
  })
}

onMounted(() => {
  const id = props.id
  if (id) {
    getDeptConfigById(id).then(data => {
      formData.value = { ...data }
    })
  } else {
    getNextShowOrder().then(data => {
      formData.value.showOrder = data
      formData.value.statusBoolean = true
    })
  }
})
</script>
